package com.zyh.flink.day07.trigger;

import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.typeutils.base.DoubleSerializer;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessAllWindowFunction;
import org.apache.flink.streaming.api.functions.windowing.delta.DeltaFunction;
import org.apache.flink.streaming.api.windowing.assigners.GlobalWindows;
import org.apache.flink.streaming.api.windowing.triggers.CountTrigger;
import org.apache.flink.streaming.api.windowing.triggers.DeltaTrigger;
import org.apache.flink.streaming.api.windowing.windows.GlobalWindow;
import org.apache.flink.util.Collector;

public class DeltaTriggerTest {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment environment = StreamExecutionEnvironment.getExecutionEnvironment();

        DataStreamSource<String> dataStreamSource = environment.socketTextStream("hadoop10", 9998);

        SingleOutputStreamOperator<String> result = dataStreamSource
                .map(new MapFunction<String, Double>() {
                    @Override
                    public Double map(String s) throws Exception {
                        return Double.valueOf(s);
                    }
                })
                .windowAll(GlobalWindows.create())
                .trigger(DeltaTrigger.of(0.1, new DeltaFunction<Double>() {
                    @Override
                    public double getDelta(Double d1, Double d2) {
                        System.out.print("d1 = " + d1);
                        System.out.println(",d2 = " + d2);
                        return d1-d2;
                    }
                },new DoubleSerializer()))
                .process(new ProcessAllWindowFunction<Double, String, GlobalWindow>() {
                    @Override
                    public void process(Context context, Iterable<Double> iterable, Collector<String> collector) throws Exception {
                        StringBuilder sb = new StringBuilder();
                        for (Double d : iterable) {
                            String s = d+"";
                            sb.append(s).append(" ");
                        }
                        collector.collect(sb.toString());
                    }
                });

        result.print();
        environment.execute("Job");
    }
}
